<?php

namespace App\Store\Controllers\Financial\Business;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Common\Services\Store\Common as StoreCommon;

use App\Common\Services\CommonExcelExport;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Financial\Business\Otherpay;
use Maatwebsite\Excel\Facades\Excel;

use App\Store\Validate\Financial\Business\OtherPay as ValidateFinancialBusinessOtherPay;
use Illuminate\Support\Facades\DB;

/**
 * 其他收支--每日录入搜索汇总
 */
class OtherPayController extends Controller
{

    public function dopostadd(Request $request){

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $current_store_id = 0;
        $store_ids = $accountinfo['store_ids'];
        if (is_array($store_ids) || $store_ids == '' || $store_ids<=0) { //获取当前权限下的门店

            return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
        }else{
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }
        $subdata=$request->subdata ?? '';
        $date_str=strtotime($request->date_str ?? '');
        $subdata=is_array($subdata) ? $subdata : (is_array(json_decode($subdata, true)) ? json_decode($subdata, true) : []);

        if($date_str<=0){
            return response()->json(['code' => '001', 'msg' => '日期未选择或格式错误']);
        }

        $date_str=date('Y-m-d',$date_str);
        $isexist=Otherpay::where([['date_str',$date_str],['cp_id',$cp_id],['store_id',$current_store_id],['is_del',1]])->first();
        if($isexist){
            return response()->json(['code' => '001', 'msg' => $date_str.'已存在记录']);
        }
        $ValidateData = new ValidateFinancialBusinessOtherPay('sdata');
        $insdata=[];
        foreach($subdata as $sdata){
            if (!$ValidateData->check($sdata)) {
                return response()->json(['code' => '001', 'msg' => $ValidateData->getError()]);
            }

            $insdata[]=[
                'cp_id'=>$cp_id,
                'store_id'=>$current_store_id,
                'abstract'=>$sdata['abstract'],
                'subject_id'=>$sdata['subject_id'],
                'in_money'=>$sdata['in_money'],
                'out_money'=>$sdata['out_money'],
                'date_str'=>$date_str,
                'create_at'=>time(),
                'update_at'=>time(),
                'create_account_id'=>$accountinfo['id'],
                'create_account_real_name'=>$accountinfo['real_name'],
                'update_account_id'=>$accountinfo['id'],
                'update_account_real_name'=>$accountinfo['real_name'],
            ];
        }


        DB::beginTransaction();
        try {
            Otherpay::insert($insdata);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '新增收支表失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '新增收支表成功']);
    }




    public function getinfo(Request $request){

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $current_store_id = 0;
        $store_ids = $accountinfo['store_ids'];
        if (is_array($store_ids) || $store_ids == '' || $store_ids<=0) { //获取当前权限下的门店

            return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
        }else{
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }
        $date_str=strtotime($request->date_str ?? '');
        if($date_str<=0){
            return response()->json(['code' => '001', 'msg' => '日期未选择或格式错误']);
        }

        $date_str=date('Y-m-d',$date_str);
        $infolist=Otherpay::with(['subjectinfo'])->where([['date_str',$date_str],['cp_id',$cp_id],['store_id',$current_store_id],['is_del',1]])->get()->toArray();

        return response()->json(['code' => '000', 'msg' => '获取成功','data'=>['infolist'=>$infolist]]);
    }


    public function dopostedit(Request $request){
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $current_store_id = 0;
        $store_ids = $accountinfo['store_ids'];
        if (is_array($store_ids) || $store_ids == '' || $store_ids<=0) { //获取当前权限下的门店

            return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
        }else{
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }
        $date_str=strtotime($request->date_str ?? '');
        if($date_str<=0){
            return response()->json(['code' => '001', 'msg' => '日期未选择或格式错误']);
        }

        $date_str=date('Y-m-d',$date_str);
        $info=Otherpay::where([['date_str',$date_str],['cp_id',$cp_id],['store_id',$current_store_id],['is_del',1]])->first();

        if(!$info){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $subdata=$request->subdata ?? '';
        $subdata=is_array($subdata) ? $subdata : (is_array(json_decode($subdata, true)) ? json_decode($subdata, true) : []);


        $ValidateData = new ValidateFinancialBusinessOtherPay('sdata');
        $insdata=[];
        foreach($subdata as $sdata){
            if (!$ValidateData->check($sdata)) {
                return response()->json(['code' => '001', 'msg' => $ValidateData->getError()]);
            }

            $insdata[]=[
                'cp_id'=>$cp_id,
                'store_id'=>$current_store_id,
                'abstract'=>$sdata['abstract'],
                'subject_id'=>$sdata['subject_id'],
                'in_money'=>$sdata['in_money'],
                'out_money'=>$sdata['out_money'],
                'date_str'=>$date_str,
                'create_at'=>time(),
                'update_at'=>time(),
                'create_account_id'=>$accountinfo['id'],
                'create_account_real_name'=>$accountinfo['real_name'],
                'update_account_id'=>$accountinfo['id'],
                'update_account_real_name'=>$accountinfo['real_name'],
            ];
        }


        DB::beginTransaction();
        try {
            Otherpay::where([['date_str',$date_str],['cp_id',$cp_id],['store_id',$current_store_id],['is_del',1]])->update(['is_del'=>2,'del_at'=>time()]);
            Otherpay::insert($insdata);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '编辑收支表失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '编辑收支表成功']);

    }

    public function getdatabysearch(Request $request)
    {
        $store_id=intval($request->store_id);
        if($store_id<=0){
            return response()->json(['code' => '001', 'msg' => '请选择门店']);
        }
        $res=Otherpay::getList($request);
        $store_name=SiteStore::where(['id'=>$store_id])->value('store_name');
        return response()->json(['code' => '000', 'msg' => '获取成功','data'=>['list'=>$res['list'],'sumdata'=>$res['sumdata'],'store_name'=>$store_name]]);
    }



    public function doexport(Request $request){
        $store_id=intval($request->store_id);
        if($store_id<=0){
            return response()->json(['code' => '001', 'msg' => '请选择门店']);
        }

        $subject_name_arr=['-1'=>'销售收入','-2'=>'销售费用','-3'=>'销售费用-商品维修费','-4'=>'销售费用-广告费和业务宣传费','-5'=>'财务费用-手续费'];

        $res=Otherpay::getList($request);
        $list=$res['list']['list'];
        $exceldata = [];
        
        $store_name=SiteStore::where(['id'=>$store_id])->value('store_name');

        $row = [
            ['keynum'=>'其他收支表'],
            ['keynum'=>'所属门店：'.$store_name],
            [
                'keynum' => '序号',
                'date_str' => '日期',
                'abstract' => '摘要',
                'subject_name' => '科目',
                'in_money' => '收入金额',
                'out_money'=>'支出金额',
            ]
        ];
        foreach($list as $key=>$val){
            $exceldata[] = [
                'keynum'=>$key+1,
                'date_str'=>$val['date_str'],
                'abstract'=>$val['abstract'],
                'subject_name'=>$val['subject_id']<0?$subject_name_arr[$val['subject_id']]:($val['subjectinfo']?$val['subjectinfo']['subject_name']:''),
                'in_money'=>$val['in_money']/100,
                'out_money'=>$val['out_money']/100,
            ];
        }

//        $exceldata[]=[
//            'keynum'=>'合计',
//            'date_str'=>'',
//            'abstract'=>'',
//            'subject_name'=>'',
//            'in_money'=>$res['sumdata']['in_money']/100,
//            'out_money'=>$res['sumdata']['out_money']/100,
//        ];

        $filename = '其他收支导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);


    }





}
